package com.web2.controller;

import com.web2.dao.BookMapper;
import com.web2.entity.Book;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "BookQuery", urlPatterns = "/query")
public class BookQuery extends HttpServlet {
    private BookMapper bookMapper;
    @Override
    public void init() throws ServletException {
        super.init();
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            bookMapper = new SqlSessionFactoryBuilder().build(is).openSession().getMapper(BookMapper.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String author = request.getParameter("author");
        try {
//            List<Book> books = BookDao.queryByAuthor(author);
            List<Book> books = bookMapper.queryByAuthor(author);
            request.setAttribute("books", books);
            request.setAttribute("display", "show");
            List<String> heads = new ArrayList();
            heads.add("Title");
            heads.add("Press");
            request.setAttribute("heads", heads);
            request.getRequestDispatcher("index.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

